home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2005 October / PCWOCT05.iso / Software / FromTheMag / XAMPP 1.4.14 / xampp-win32-1.4.14-installer.exe / xampp / php / pear / MDB.php < prev    next >
PHP Script  |  2004-03-24  |  27KB  |  736 lines

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP Version 4                                                        |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
  6. // | Stig. S. Bakken, Lukas Smith                                         |
  7. // | All rights reserved.                                                 |
  8. // +----------------------------------------------------------------------+
  9. // | MDB is a merge of PEAR DB and Metabases that provides a unified DB   |
  10. // | API as well as database abstraction for PHP applications.            |
  11. // | This LICENSE is in the BSD license style.                            |
  12. // |                                                                      |
  13. // | Redistribution and use in source and binary forms, with or without   |
  14. // | modification, are permitted provided that the following conditions   |
  15. // | are met:                                                             |
  16. // |                                                                      |
  17. // | Redistributions of source code must retain the above copyright       |
  18. // | notice, this list of conditions and the following disclaimer.        |
  19. // |                                                                      |
  20. // | Redistributions in binary form must reproduce the above copyright    |
  21. // | notice, this list of conditions and the following disclaimer in the  |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // |                                                                      |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission.                                                  |
  28. // |                                                                      |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
  40. // | POSSIBILITY OF SUCH DAMAGE.                                          |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Lukas Smith <smith@backendmedia.com>                         |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: MDB.php,v 1.59.4.4 2004/01/08 13:43:04 lsmith Exp $
  46. //
  47. require_once('PEAR.php');
  48.  
  49. /**
  50.  * The method mapErrorCode in each MDB_dbtype implementation maps
  51.  * native error codes to one of these.
  52.  *
  53.  * If you add an error code here, make sure you also add a textual
  54.  * version of it in MDB::errorMessage().
  55.  */
  56.  
  57. define('MDB_OK',                         1);
  58. define('MDB_ERROR',                     -1);
  59. define('MDB_ERROR_SYNTAX',              -2);
  60. define('MDB_ERROR_CONSTRAINT',          -3);
  61. define('MDB_ERROR_NOT_FOUND',           -4);
  62. define('MDB_ERROR_ALREADY_EXISTS',      -5);
  63. define('MDB_ERROR_UNSUPPORTED',         -6);
  64. define('MDB_ERROR_MISMATCH',            -7);
  65. define('MDB_ERROR_INVALID',             -8);
  66. define('MDB_ERROR_NOT_CAPABLE',         -9);
  67. define('MDB_ERROR_TRUNCATED',          -10);
  68. define('MDB_ERROR_INVALID_NUMBER',     -11);
  69. define('MDB_ERROR_INVALID_DATE',       -12);
  70. define('MDB_ERROR_DIVZERO',            -13);
  71. define('MDB_ERROR_NODBSELECTED',       -14);
  72. define('MDB_ERROR_CANNOT_CREATE',      -15);
  73. define('MDB_ERROR_CANNOT_DELETE',      -16);
  74. define('MDB_ERROR_CANNOT_DROP',        -17);
  75. define('MDB_ERROR_NOSUCHTABLE',        -18);
  76. define('MDB_ERROR_NOSUCHFIELD',        -19);
  77. define('MDB_ERROR_NEED_MORE_DATA',     -20);
  78. define('MDB_ERROR_NOT_LOCKED',         -21);
  79. define('MDB_ERROR_VALUE_COUNT_ON_ROW', -22);
  80. define('MDB_ERROR_INVALID_DSN',        -23);
  81. define('MDB_ERROR_CONNECT_FAILED',     -24);
  82. define('MDB_ERROR_EXTENSION_NOT_FOUND',-25);
  83. define('MDB_ERROR_NOSUCHDB',           -26);
  84. define('MDB_ERROR_ACCESS_VIOLATION',   -27);
  85. define('MDB_ERROR_CANNOT_REPLACE',     -28);
  86. define('MDB_ERROR_CANNOT_ALTER',       -29);
  87. define('MDB_ERROR_MANAGER',            -30);
  88. define('MDB_ERROR_MANAGER_PARSE',      -31);
  89. define('MDB_ERROR_LOADMODULE',         -32);
  90. define('MDB_ERROR_INSUFFICIENT_DATA',  -33);
  91.  
  92. /**
  93.  * This is a special constant that tells DB the user hasn't specified
  94.  * any particular get mode, so the default should be used.
  95.  */
  96.  
  97. define('MDB_FETCHMODE_DEFAULT', 0);
  98.  
  99. /**
  100.  * Column data indexed by numbers, ordered from 0 and up
  101.  */
  102.  
  103. define('MDB_FETCHMODE_ORDERED',  1);
  104.  
  105. /**
  106.  * Column data indexed by column names
  107.  */
  108.  
  109. define('MDB_FETCHMODE_ASSOC',    2);
  110.  
  111. /**
  112.  * For multi-dimensional results: normally the first level of arrays
  113.  * is the row number, and the second level indexed by column number or name.
  114.  * MDB_FETCHMODE_FLIPPED switches this order, so the first level of arrays
  115.  * is the column name, and the second level the row number.
  116.  */
  117.  
  118. define('MDB_FETCHMODE_FLIPPED',  4);
  119.  
  120. /**
  121.  * These are constants for the tableInfo-function
  122.  * they are bitwised or'ed. so if there are more constants to be defined
  123.  * in the future, adjust MDB_TABLEINFO_FULL accordingly
  124.  */
  125.  
  126. define('MDB_TABLEINFO_ORDER',      1);
  127. define('MDB_TABLEINFO_ORDERTABLE', 2);
  128. define('MDB_TABLEINFO_FULL',       3);
  129.  
  130. /**
  131.  * These are constants for each of the supported datatypes
  132.  */
  133.  
  134. define('MDB_TYPE_TEXT'      , 0);
  135. define('MDB_TYPE_BOOLEAN'   , 1);
  136. define('MDB_TYPE_INTEGER'   , 2);
  137. define('MDB_TYPE_DECIMAL'   , 3);
  138. define('MDB_TYPE_FLOAT'     , 4);
  139. define('MDB_TYPE_DATE'      , 5);
  140. define('MDB_TYPE_TIME'      , 6);
  141. define('MDB_TYPE_TIMESTAMP' , 7);
  142. define('MDB_TYPE_CLOB'      , 8);
  143. define('MDB_TYPE_BLOB'      , 9);
  144.  
  145. /**
  146.  * These are global variables that are used to track the various class instances
  147.  */
  148.  
  149. $GLOBALS['_MDB_lobs'] = array();
  150. $GLOBALS['_MDB_databases'] = array();
  151.  
  152. /**
  153.  * The main 'MDB' class is simply a container class with some static
  154.  * methods for creating DB objects as well as some utility functions
  155.  * common to all parts of DB.
  156.  *
  157.  * The object model of DB is as follows (indentation means inheritance):
  158.  *
  159.  * MDB          The main DB class.  This is simply a utility class
  160.  *              with some 'static' methods for creating MDB objects as
  161.  *              well as common utility functions for other MDB classes.
  162.  *
  163.  * MDB_common   The base for each DB implementation.  Provides default
  164.  * |            implementations (in OO lingo virtual methods) for
  165.  * |            the actual DB implementations as well as a bunch of
  166.  * |            query utility functions.
  167.  * |
  168.  * +-MDB_mysql  The DB implementation for MySQL. Inherits MDB_Common.
  169.  *              When calling MDB::factory or MDB::connect for MySQL
  170.  *              connections, the object returned is an instance of this
  171.  *              class.
  172.  * +-MDB_pgsql  The DB implementation for PostGreSQL. Inherits MDB_Common.
  173.  *              When calling MDB::factory or MDB::connect for PostGreSQL
  174.  *              connections, the object returned is an instance of this
  175.  *              class.
  176.  *
  177.  * MDB_Date     This class provides several method to convert from and to
  178.  *              MDB timestamps.
  179.  *
  180.  * MDB_Manager  This class handles the xml schema management.
  181.  *
  182.  * @package  MDB
  183.  * @version  $Id: MDB.php,v 1.59.4.4 2004/01/08 13:43:04 lsmith Exp $
  184.  * @category Database
  185.  * @author   Lukas Smith <smith@backendmedia.com>
  186.  */
  187. class MDB
  188. {
  189.     // }}}
  190.     // {{{ setOptions()
  191.     
  192.     /**
  193.      * set option array in an exiting database object
  194.      *
  195.      * @param   object  $db       MDB object
  196.      * @param   mixed   $options  An associative array of option names and
  197.      *                            their values.
  198.      * @access  public
  199.      */
  200.     function setOptions(&$db, $options)
  201.     {
  202.         if(is_array($options)) {
  203.             foreach($options as $option => $value) {
  204.                 $test = $db->setOption($option, $value);
  205.                 if(MDB::isError($test)) {
  206.                     return $test;
  207.                 }
  208.             }
  209.         } else {
  210.             $db->setOption('persistent', $options);
  211.         }
  212.         $include_lob = $db->getOption('includelob');
  213.         if(!MDB::isError($include_lob) && $include_lob) {
  214.             $db->loadLob('load at start');
  215.         }
  216.         $includemanager = $db->getOption('includemanager');
  217.         if(!MDB::isError($includemanager) && $includemanager) {
  218.             $db->loadManager('load at start');
  219.         }
  220.         $debug = $db->getOption('debug');
  221.         if(!MDB::isError($debug) && $debug) {
  222.             $db->captureDebugOutput(TRUE);
  223.         }
  224.     }
  225.     
  226.     // }}}
  227.     // {{{ factory()
  228.     
  229.     /**
  230.      * Create a new DB connection object for the specified database
  231.      * type
  232.      * IMPORTANT: In order for MDB to work properly it is necessary that
  233.      * you make sure that you work with a reference of the original
  234.      * object instead of a copy (this is a PHP4 quirk).
  235.      *
  236.      * For example:
  237.      *     $mdb =& MDB::factory($dsn);
  238.      *          ^^
  239.      * And not:
  240.      *     $mdb = MDB::factory($dsn);
  241.      *          ^^
  242.      *
  243.      * @param   string  $type   database type, for example 'mysql'
  244.      * @return  mixed   a newly created MDB connection object, or a MDB
  245.      *                  error object on error
  246.      * @access  public
  247.      */
  248.     function &factory($type)
  249.     {
  250.         $class_name = "MDB_$type";
  251.         
  252.         @include_once("MDB/${type}.php");
  253.         
  254.         @$db =& new $class_name;
  255.         
  256.         return($db);
  257.     }
  258.     
  259.     // }}}
  260.     // {{{ connect()
  261.     
  262.     /**
  263.      * Create a new MDB connection object and connect to the specified
  264.      * database
  265.      *
  266.      * IMPORTANT: In order for MDB to work properly it is necessary that
  267.      * you make sure that you work with a reference of the original
  268.      * object instead of a copy (this is a PHP4 quirk).
  269.      *
  270.      * For example:
  271.      *     $mdb =& MDB::connect($dsn);
  272.      *          ^^
  273.      * And not:
  274.      *     $mdb = MDB::connect($dsn);
  275.      *          ^^
  276.      *
  277.      * @param   mixed   $dsn      'data source name', see the MDB::parseDSN
  278.      *                            method for a description of the dsn format.
  279.      *                            Can also be specified as an array of the
  280.      *                            format returned by MDB::parseDSN.
  281.      * @param   mixed   $options  An associative array of option names and
  282.      *                            their values.
  283.      * @return  mixed   a newly created MDB connection object, or a MDB
  284.      *                  error object on error
  285.      * @access  public
  286.      * @see     MDB::parseDSN
  287.      */
  288.     function &connect($dsn, $options = FALSE)
  289.     {
  290.         $dsninfo = MDB::parseDSN($dsn);
  291.         if(isset($dsninfo['phptype'])) {
  292.             $type          = $dsninfo['phptype'];
  293.             $class_name    = 'MDB_'.$type;
  294.             $include       = 'MDB/'.$type.'.php';
  295.         } else {
  296.             return(PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND,
  297.                 NULL, NULL, 'no RDBMS driver specified',
  298.                 'MDB_Error', TRUE));
  299.         }
  300.         
  301.         if(is_array($options)
  302.             && isset($options['debug'])
  303.             && $options['debug'] >= 2
  304.         ) {
  305.             // expose php errors with sufficient debug level
  306.             @include_once($include);
  307.         } else {
  308.             include_once($include);
  309.         }
  310.         
  311.         if(!class_exists($class_name)) {
  312.             $error = PEAR::raiseError(NULL, MDB_ERROR_NOT_FOUND, NULL, NULL,
  313.                 'Unable to include the '.$include.' file', 'MDB_Error', TRUE);
  314.             return($error);
  315.         }
  316.         
  317.         @$db =& new $class_name();
  318.         
  319.         $db->setDSN($dsninfo);
  320.         
  321.         MDB::setOptions($db, $options);
  322.         
  323.         if(isset($dsninfo['database'])) {
  324.             $err = $db->connect();
  325.             if (MDB::isError($err)) {
  326.                 $dsn = $db->getDSN();
  327.                 $err->addUserInfo($dsn);
  328.                 return($err);
  329.             }
  330.         }
  331.         return($db);
  332.     }
  333.     
  334.     // }}}
  335.     // {{{ connect()
  336.     
  337.     /**
  338.      * Returns a MDB connection with the requested DSN.
  339.      * A newnew MDB connection object is only created if no object with the 
  340.      * reuested DSN exists yet.
  341.      *
  342.      * IMPORTANT: In order for MDB to work properly it is necessary that
  343.      * you make sure that you work with a reference of the original
  344.      * object instead of a copy (this is a PHP4 quirk).
  345.      *
  346.      * For example:
  347.      *     $mdb =& MDB::sngleton($dsn);
  348.      *          ^^
  349.      * And not:
  350.      *     $mdb = MDB::singleton($dsn);
  351.      *          ^^
  352.      *
  353.      * @param   mixed   $dsn      'data source name', see the MDB::parseDSN
  354.      *                            method for a description of the dsn format.
  355.      *                            Can also be specified as an array of the
  356.      *                            format returned by MDB::parseDSN.
  357.      * @param   mixed   $options  An associative array of option names and
  358.      *                            their values.
  359.      * @return  mixed   a newly created MDB connection object, or a MDB
  360.      *                  error object on error
  361.      * @access  public
  362.      * @see     MDB::parseDSN
  363.      */
  364.     function &singleton($dsn = NULL, $options = FALSE)
  365.     {
  366.         if ($dsn) {
  367.             $dsninfo = MDB::parseDSN($dsn);
  368.             $dsninfo_default = array(
  369.                 'phptype' => NULL,
  370.                 'username' => NULL,
  371.                 'password' => NULL,
  372.                 'hostspec' => NULL,
  373.                 'database' => NULL,
  374.             );
  375.             $dsninfo = array_merge($dsninfo_default, $dsninfo);
  376.             $keys = array_keys($GLOBALS['_MDB_databases']);
  377.             for ($i=0, $j=count($keys); $i<$j; ++$i) {
  378.                 $tmp_dsn = $GLOBALS['_MDB_databases'][$keys[$i]]->getDSN('array');
  379.                 if ($dsninfo['phptype'] == $tmp_dsn['phptype']
  380.                     && $dsninfo['username'] == $tmp_dsn['username']
  381.                     && $dsninfo['password'] == $tmp_dsn['password']
  382.                     && $dsninfo['hostspec'] == $tmp_dsn['hostspec']
  383.                     && $dsninfo['database'] == $tmp_dsn['database'])
  384.                 {
  385.                     MDB::setOptions($GLOBALS['_MDB_databases'][$keys[$i]], $options);
  386.                     return $GLOBALS['_MDB_databases'][$keys[$i]];
  387.                 }
  388.             }
  389.         } else {
  390.             if (is_array($GLOBALS['_MDB_databases'])
  391.                 && reset($GLOBALS['_MDB_databases'])
  392.             ) {
  393.                 $db =& $GLOBALS['_MDB_databases'][key($GLOBALS['_MDB_databases'])];
  394.                 return $db;
  395.             }
  396.         }
  397.         $db =& MDB::connect($dsn, $options);
  398.         return $db;
  399.     }
  400.     
  401.     // }}}
  402.     // {{{ loadFile()
  403.     
  404.     /**
  405.      * load a file (like 'Date.php' or 'Manager.php')
  406.      *
  407.      * @return $file    name of the file to be included from the MDB dir without
  408.      *                  the '.php' extension (like 'Date' or 'Manager')
  409.      * @access public
  410.      */
  411.     function loadFile($file)
  412.     {
  413.         @include_once('MDB/'.$file.'.php');
  414.     }
  415.     
  416.     // }}}
  417.     // {{{ apiVersion()
  418.     
  419.     /**
  420.      * Return the MDB API version
  421.      *
  422.      * @return int     the MDB API version number
  423.      * @access public
  424.      */
  425.     function apiVersion()
  426.     {
  427.         return(1);
  428.     }
  429.     
  430.     // }}}
  431.     // {{{ isError()
  432.     
  433.     /**
  434.      * Tell whether a result code from a MDB method is an error
  435.      *
  436.      * @param   int       $value  result code
  437.      * @return  boolean   whether $value is an MDB_Error
  438.      * @access public
  439.      */
  440.     function isError($value)
  441.     {
  442.         return(is_object($value)
  443.             && (get_class($value) == 'mdb_error'
  444.                 || is_subclass_of($value, 'mdb_error'))
  445.         );
  446.     }
  447.     
  448.     // }}}
  449.     // {{{ isConnection()
  450.     /**
  451.      * Tell whether a value is a MDB connection
  452.      *
  453.      * @param mixed $value value to test
  454.      *
  455.      * @return bool whether $value is a MDB connection
  456.      *
  457.      * @access public
  458.      */
  459.     function isConnection($value)
  460.     {
  461.         return (is_object($value)
  462.             && is_subclass_of($value, 'mdb_common')
  463.         );
  464.     }
  465.     
  466.     // }}}
  467.     // {{{ isManip()
  468.     
  469.     /**
  470.      * Tell whether a query is a data manipulation query (insert,
  471.      * update or delete) or a data definition query (create, drop,
  472.      * alter, grant, revoke).
  473.      *
  474.      * @param   string   $query the query
  475.      * @return  boolean  whether $query is a data manipulation query
  476.      * @access public
  477.      */
  478.     function isManip($query)
  479.     {
  480.         $manips = 'INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|
  481.                   ALTER|GRANT|REVOKE|LOCK|UNLOCK|ROLLBACK|COMMIT';
  482.         if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) {
  483.             return(TRUE);
  484.         }
  485.         return(FALSE);
  486.     }
  487.     
  488.     // }}}
  489.     // {{{ errorMessage()
  490.     
  491.     /**
  492.      * Return a textual error message for a MDB error code
  493.      *
  494.      * @param   int     $value error code
  495.      * @return  string  error message, or false if the error code was
  496.      *                  not recognized
  497.      * @access public
  498.      */
  499.     function errorMessage($value)
  500.     {
  501.         static $errorMessages;
  502.         if (!isset($errorMessages)) {
  503.             $errorMessages = array(
  504.                 MDB_ERROR                    => 'unknown error',
  505.                 MDB_ERROR_ALREADY_EXISTS     => 'already exists',
  506.                 MDB_ERROR_CANNOT_CREATE      => 'can not create',
  507.                 MDB_ERROR_CANNOT_ALTER       => 'can not alter',
  508.                 MDB_ERROR_CANNOT_REPLACE     => 'can not replace',
  509.                 MDB_ERROR_CANNOT_DELETE      => 'can not delete',
  510.                 MDB_ERROR_CANNOT_DROP        => 'can not drop',
  511.                 MDB_ERROR_CONSTRAINT         => 'constraint violation',
  512.                 MDB_ERROR_DIVZERO            => 'division by zero',
  513.                 MDB_ERROR_INVALID            => 'invalid',
  514.                 MDB_ERROR_INVALID_DATE       => 'invalid date or time',
  515.                 MDB_ERROR_INVALID_NUMBER     => 'invalid number',
  516.                 MDB_ERROR_MISMATCH           => 'mismatch',
  517.                 MDB_ERROR_NODBSELECTED       => 'no database selected',
  518.                 MDB_ERROR_NOSUCHFIELD        => 'no such field',
  519.                 MDB_ERROR_NOSUCHTABLE        => 'no such table',
  520.                 MDB_ERROR_NOT_CAPABLE        => 'MDB backend not capable',
  521.                 MDB_ERROR_NOT_FOUND          => 'not found',
  522.                 MDB_ERROR_NOT_LOCKED         => 'not locked',
  523.                 MDB_ERROR_SYNTAX             => 'syntax error',
  524.                 MDB_ERROR_UNSUPPORTED        => 'not supported',
  525.                 MDB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
  526.                 MDB_ERROR_INVALID_DSN        => 'invalid DSN',
  527.                 MDB_ERROR_CONNECT_FAILED     => 'connect failed',
  528.                 MDB_OK                       => 'no error',
  529.                 MDB_ERROR_NEED_MORE_DATA     => 'insufficient data supplied',
  530.                 MDB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
  531.                 MDB_ERROR_NOSUCHDB           => 'no such database',
  532.                 MDB_ERROR_ACCESS_VIOLATION   => 'insufficient permissions',
  533.                 MDB_ERROR_MANAGER            => 'MDB_manager error',
  534.                 MDB_ERROR_MANAGER_PARSE      => 'MDB_manager schema parse error',
  535.                 MDB_ERROR_LOADMODULE         => 'Error while including on demand module',
  536.                 MDB_ERROR_TRUNCATED          => 'truncated'
  537.             );
  538.         }
  539.         
  540.         if (MDB::isError($value)) {
  541.             $value = $value->getCode();
  542.         }
  543.         
  544.         return(isset($errorMessages[$value]) ?
  545.            $errorMessages[$value] : $errorMessages[MDB_ERROR]);
  546.     }
  547.     
  548.     // }}}
  549.     // {{{ parseDSN()
  550.     
  551.     /**
  552.      * Parse a data source name
  553.      *
  554.      * A array with the following keys will be returned:
  555.      *  phptype: Database backend used in PHP (mysql, odbc etc.)
  556.      *  dbsyntax: Database used with regards to SQL syntax etc.
  557.      *  protocol: Communication protocol to use (tcp, unix etc.)
  558.      *  hostspec: Host specification (hostname[:port])
  559.      *  database: Database to use on the DBMS server
  560.      *  username: User name for login
  561.      *  password: Password for login
  562.      *
  563.      * The format of the supplied DSN is in its fullest form:
  564.      *
  565.      *  phptype(dbsyntax)://username:password@protocol+hostspec/database
  566.      *
  567.      * Most variations are allowed:
  568.      *
  569.      *  phptype://username:password@protocol+hostspec:110//usr/db_file.db
  570.      *  phptype://username:password@hostspec/database_name
  571.      *  phptype://username:password@hostspec
  572.      *  phptype://username@hostspec
  573.      *  phptype://hostspec/database
  574.      *  phptype://hostspec
  575.      *  phptype(dbsyntax)
  576.      *  phptype
  577.      *
  578.      * @param   string  $dsn Data Source Name to be parsed
  579.      * @return  array   an associative array
  580.      * @access public
  581.      * @author Tomas V.V.Cox <cox@idecnet.com>
  582.      */
  583.     function parseDSN($dsn)
  584.     {
  585.         if (is_array($dsn)) {
  586.             return($dsn);
  587.         }
  588.         
  589.         $parsed = array(
  590.             'phptype'  => FALSE,
  591.             'dbsyntax' => FALSE,
  592.             'username' => FALSE,
  593.             'password' => FALSE,
  594.             'protocol' => FALSE,
  595.             'hostspec' => FALSE,
  596.             'port'     => FALSE,
  597.             'socket'   => FALSE,
  598.             'database' => FALSE
  599.         );
  600.         
  601.         // Find phptype and dbsyntax
  602.         if (($pos = strpos($dsn, '://')) !== FALSE) {
  603.             $str = substr($dsn, 0, $pos);
  604.             $dsn = substr($dsn, $pos + 3);
  605.         } else {
  606.             $str = $dsn;
  607.             $dsn = NULL;
  608.         }
  609.         
  610.         // Get phptype and dbsyntax
  611.         // $str => phptype(dbsyntax)
  612.         if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
  613.             $parsed['phptype']  = $arr[1];
  614.             $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
  615.         } else {
  616.             $parsed['phptype']  = $str;
  617.             $parsed['dbsyntax'] = $str;
  618.         }
  619.         
  620.         if (empty($dsn)) {
  621.             return($parsed);
  622.         }
  623.         
  624.         // Get (if found): username and password
  625.         // $dsn => username:password@protocol+hostspec/database
  626.         if (($at = strrpos($dsn,'@')) !== FALSE) {
  627.             $str = substr($dsn, 0, $at);
  628.             $dsn = substr($dsn, $at + 1);
  629.             if (($pos = strpos($str, ':')) !== FALSE) {
  630.                 $parsed['username'] = rawurldecode(substr($str, 0, $pos));
  631.                 $parsed['password'] = rawurldecode(substr($str, $pos + 1));
  632.             } else {
  633.                 $parsed['username'] = rawurldecode($str);
  634.             }
  635.         }
  636.         
  637.         // Find protocol and hostspec
  638.         
  639.         // $dsn => proto(proto_opts)/database
  640.         if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
  641.             $proto       = $match[1];
  642.             $proto_opts  = (!empty($match[2])) ? $match[2] : FALSE;
  643.             $dsn         = $match[3];
  644.         
  645.         // $dsn => protocol+hostspec/database (old format)
  646.         } else {
  647.             if (strpos($dsn, '+') !== FALSE) {
  648.                 list($proto, $dsn) = explode('+', $dsn, 2);
  649.             }
  650.             if (strpos($dsn, '/') !== FALSE) {
  651.                 list($proto_opts, $dsn) = explode('/', $dsn, 2);
  652.             } else {
  653.                 $proto_opts = $dsn;
  654.                 $dsn = NULL;
  655.             }
  656.         }
  657.         
  658.         // process the different protocol options
  659.         $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
  660.         $proto_opts = rawurldecode($proto_opts);
  661.         if ($parsed['protocol'] == 'tcp') {
  662.             if (strpos($proto_opts, ':') !== FALSE) {
  663.                 list($parsed['hostspec'], $parsed['port']) =
  664.                                                      explode(':', $proto_opts);
  665.             } else {
  666.                 $parsed['hostspec'] = $proto_opts;
  667.             }
  668.         } elseif ($parsed['protocol'] == 'unix') {
  669.             $parsed['socket'] = $proto_opts;
  670.         }
  671.         
  672.         // Get dabase if any
  673.         // $dsn => database
  674.         if (!empty($dsn)) {
  675.             // /database
  676.             if (($pos = strpos($dsn, '?')) === FALSE) {
  677.                 $parsed['database'] = $dsn;
  678.             // /database?param1=value1¶m2=value2
  679.             } else {
  680.                 $parsed['database'] = substr($dsn, 0, $pos);
  681.                 $dsn = substr($dsn, $pos + 1);
  682.                 if (strpos($dsn, '&') !== FALSE) {
  683.                     $opts = explode('&', $dsn);
  684.                 } else { // database?param1=value1
  685.                     $opts = array($dsn);
  686.                 }
  687.                 foreach ($opts as $opt) {
  688.                     list($key, $value) = explode('=', $opt);
  689.                     if (!isset($parsed[$key])) { // don't allow params overwrite
  690.                         $parsed[$key] = rawurldecode($value);
  691.                     }
  692.                 }
  693.             }
  694.         }
  695.         
  696.         return($parsed);
  697.     }
  698. }
  699.  
  700. /**
  701.  * MDB_Error implements a class for reporting portable database error
  702.  * messages.
  703.  *
  704.  * @package MDB
  705.  * @category Database
  706.  * @author  Stig Bakken <ssb@fast.no>
  707.  */
  708. class MDB_Error extends PEAR_Error
  709. {
  710.     
  711.     // }}}
  712.     // {{{ constructor
  713.     
  714.     /**
  715.      * MDB_Error constructor.
  716.      *
  717.      * @param mixed   $code      MDB error code, or string with error message.
  718.      * @param integer $mode      what 'error mode' to operate in
  719.      * @param integer $level     what error level to use for
  720.      *                           $mode & PEAR_ERROR_TRIGGER
  721.      * @param smixed  $debuginfo additional debug info, such as the last query
  722.      */
  723.     function MDB_Error($code = MDB_ERROR, $mode = PEAR_ERROR_RETURN,
  724.               $level = E_USER_NOTICE, $debuginfo = NULL)
  725.     {
  726.         if (is_int($code)) {
  727.             $this->PEAR_Error('MDB Error: '.MDB::errorMessage($code), $code,
  728.                 $mode, $level, $debuginfo);
  729.         } else {
  730.             $this->PEAR_Error("MDB Error: $code", MDB_ERROR, $mode, $level,
  731.                 $debuginfo);
  732.         }
  733.     }
  734. }
  735. ?>
  736.